package com.zeldu.uaa.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zeldu.common.exception.CustomException;
import com.zeldu.common.model.response.CommonCode;
import com.zeldu.common.model.response.ResponseResult;
import com.zeldu.uaa.entity.Student;
import com.zeldu.uaa.entity.Teacher;
import com.zeldu.uaa.mapper.StudentMapper;
import com.zeldu.uaa.mapper.TeacherMapper;
import com.zeldu.uaa.util.JWTInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.prefs.BackingStoreException;

@Service
public class SignService {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    TeacherMapper teacherMapper;
    public ResponseResult SignIn(String email,  String userName,String password,
                                 String code, String realName,String identity){


        if(StringUtils.isBlank(email)||StringUtils.isBlank(userName)||StringUtils.isBlank(password)
                ||StringUtils.isBlank(code)||StringUtils.isBlank(identity)){
            throw new CustomException(CommonCode.FAIL);
        }

         String val_code = (String) redisTemplate.opsForValue().get(email);
         if("".equals(val_code)||val_code==null|| !val_code.equals(code)){
             redisTemplate.delete(email);
             throw new CustomException(CommonCode.Wrong_Code);
         }
         redisTemplate.delete(email);
         if(identity.equals("teacher")){
              Integer count = teacherMapper.selectCount(new LambdaQueryWrapper<Teacher>().eq(Teacher::getUserName, userName));

             if(count>0){
                  throw new CustomException(CommonCode.Exist_UserName);
              }
             Integer count1 = teacherMapper.selectCount(new LambdaQueryWrapper<Teacher>().eq(Teacher::getEmailAddr, email));
              if(count1>0){
                  throw new CustomException(CommonCode.Exist_Email);
              }

             Teacher teacher=new Teacher();
              String encodePwd = passwordEncoder.encode(password);
              teacher.setRealName(realName);
              teacher.setUserName(userName);
              teacher.setEmailAddr(email);
              teacher.setPassWord(encodePwd);
            try {
                teacherMapper.insert(teacher);
            }catch (Exception e){
                throw new CustomException(CommonCode.FAIL);

            }
         }else if(identity.equals("student")){
             Integer count = studentMapper.selectCount(new LambdaQueryWrapper<Student>().eq(Student::getUserName, userName));
             if(count>0){
                 throw new CustomException(CommonCode.Exist_UserName);
             }
             Integer count1 = studentMapper.selectCount(new LambdaQueryWrapper<Student>().eq(Student::getEmailAddr, email));
             if(count1>0){
                 throw new CustomException(CommonCode.Exist_Email);
             }
             Student student=new Student();
             String encodePwd = passwordEncoder.encode(password);
             student.setPassWord(encodePwd);
             student.setUserName(userName);
             student.setRealName(realName);
             student.setEmailAddr(email);
             try {
                 studentMapper.insert(student);
             }catch (Exception e){
                 throw new CustomException(CommonCode.FAIL);
             }

         }


        return new ResponseResult(CommonCode.SUCCESS);
    }
    @Transactional
    public ResponseResult findPwdBack(String code, String newPwd, String email,String identity) {
         String vcode = redisTemplate.opsForValue().get(email);
         if(vcode==null){
             throw new CustomException(CommonCode.Wrong_Expire);
         }
         if(vcode==null||!vcode.equals(code)){
             throw new CustomException(CommonCode.Wrong_Code);
         }

         redisTemplate.delete(email);//Del redis 的key
         if(identity.equals("student")){
             studentMapper.findPwdBack(email,passwordEncoder.encode(newPwd));
             return new ResponseResult(CommonCode.SUCCESS);
         }else if(identity.equals("teacher")){
            teacherMapper.findPwdBack(email,passwordEncoder.encode(newPwd));
            return new ResponseResult(CommonCode.SUCCESS);
         }

         return new ResponseResult(CommonCode.FAIL);

    }
    @Transactional
    public ResponseResult ChangePwd(String oldPwd, String newPwd,String identity) {
        if(identity.equals("student")){
            Student student =null;
            try {
          student=  JWTInfo.getStudentJwt();
            }catch (Exception e){
                throw new CustomException(CommonCode.Wrong_User);
            }
            String opwd = studentMapper.selectPwd(student.getId());
             boolean matches = passwordEncoder.matches(oldPwd,
                    opwd);
             if(!matches) throw new CustomException(CommonCode.Wrong_OldPwd);
            studentMapper.ChangPwd(student.getId(),passwordEncoder.encode(newPwd));
            return new ResponseResult(CommonCode.SUCCESS);

        }else if(identity.equals("teacher")){
            Teacher teacherJwt = null;
            try {
                 teacherJwt = JWTInfo.getTeacherJwt();
            }catch (Exception e){
                throw new CustomException(CommonCode.Wrong_User);
            }

            String opwd = teacherMapper.selectPwd(teacherJwt.getId());
            boolean matches = passwordEncoder.matches(oldPwd,
                    opwd);
            if(!matches) throw new CustomException(CommonCode.Wrong_OldPwd);

            teacherMapper.ChangPwd(teacherJwt.getId(),passwordEncoder.encode(newPwd));
            return new ResponseResult(CommonCode.SUCCESS);

        }
        return new ResponseResult(CommonCode.FAIL);
    }
}
